<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="classify">
        <el-select v-model="queryParams.classify" placeholder="请选择" clearable>
          <el-option
            v-for="item in classifyOption"
            :key="item.dictCode"
            :label="item.dictLabel"
            :value="item.dictCode"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="公开" prop="classify">
        <el-select v-model="queryParams.externalDisplay" placeholder="请选择" clearable>
          <el-option
            key="open"
            label="公开"
            value="1"
          >
          </el-option>
          <el-option
            key="noOpen"
            label="不公开"
            value="0"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['compilation:compilation:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['compilation:compilation:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['compilation:compilation:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['compilation:compilation:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="compilationList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="标题" width="600" prop="title" :show-overflow-tooltip="true"/>
      <el-table-column label="封面图" align="center" prop="coverImage">
        <template slot-scope="scope">
          <el-popover placement="top-start" title="" trigger="hover">
            <img :src="scope.row.coverImage" alt="" style="width: 150px;height: 150px">
            <img slot="reference" :src="scope.row.coverImage" style="width: 30px;height: 30px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="描述" prop="descri" :show-overflow-tooltip="true">


      </el-table-column>
      <el-table-column label="分类" align="center" prop="classifyStr"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="对外展示" align="externalDisplay" prop="externalDisplay">

        <template slot-scope="scope">
          <el-switch
            v-model=" scope.row.externalDisplay"
            @change="changeExternalDisplay(scope.row)"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['compilation:compilation:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['compilation:compilation:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改合集对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入标题"/>
        </el-form-item>
        <el-form-item label="分类" prop="classify">
          <el-select v-model="form.classify" placeholder="请选择" clearable>
            <el-option
              v-for="item in classifyOption"
              :key="item.dictCode"
              :label="item.dictLabel"
              :value="item.dictCode"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="是否公开" prop="externalDisplay">
          <el-switch
            v-model="form.externalDisplay"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          >
          </el-switch>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImage">
          <el-upload
            :headers="authorization"
            class="avatar-uploader"
            :action="uploadUrl"
            :show-file-list="false"
            :on-success="onSuccess"
            :before-upload="beforeAvatarUpload"
          >

            <i v-if="!coverImage" class="el-icon-plus avatar-uploader-icon"></i>
            <img height="300px" width="500px" v-if="coverImage" :src="form.coverImage" class="avatar">
          </el-upload>

        </el-form-item>
        <el-form-item label="描述" prop="descri">
          <el-input v-model="form.descri" placeholder="请输入描述"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addCompilation,
  delCompilation,
  getCompilation,
  listCompilation,
  updateCompilation
} from '@/api/compilation/compilation'
import {getToken} from '@/utils/auth'
import {listData} from '@/api/system/dict/data'

export default {
  name: 'Compilation',
  data() {
    return {
      fileList: [],
      authorization: {Authorization: 'Bearer ' + getToken()}, // 上传的图片服务器地址
      uploadUrl: process.env.VUE_APP_BASE_API + '/file/upload', // 上传的图片服务器地址
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 合集表格数据
      compilationList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        descri: null,
        coverImage: null,
        deleted: null,
        externalDisplay: null
      },
      classifyOption: [],
      // 表单参数
      form: {
        coverImage: null, title: null,
        descri: null,
        deleted: null,
        externalDisplay: 1
      },
      // 表单校验
      rules: {},
      //图片地址
      imageUrl: '',
      coverImage: ''
    }
  },
  created() {
    this.getList()
    listData({'dictType': 'compilation_type', 'pageSize': 99999}).then(response => {
      this.classifyOption = response.rows
    })
  },
  methods: {
    changeExternalDisplay(row) {
      console.log(row)
      this.$modal.confirm('是否确认改变合集编号为"' + row.id + '"的展示状态吗？').then(function () {
        return updateCompilation({
          id: row.id,
          externalDisplay: row.externalDisplay
        })
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('改变成功')
      }).catch(() => {
        row.externalDisplay = (row.externalDisplay + 1) % 2
      })
    },
    onSuccess(files, fileList) {
      this.form.coverImage = files.data.url
      this.coverImage = this.form.coverImage
    },
    onExceed(files, fileList) {
      this.$alert('已达到限制')
    },
    /** 查询合集列表 */
    getList() {
      this.loading = true
      listCompilation(this.queryParams).then(response => {
        this.compilationList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        descri: null,
        deleted: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        classify: null,
        classifyStr: null,
        remark: null,
        externalDisplay: 1
      }
      this.resetForm('form')
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        // this.$message.error('上传头像图片只能是 JPG 格式!');
      }

      return true
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加合集'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getCompilation(id).then(response => {
        this.form = response.data
        this.coverImage = this.form.coverImage
        this.open = true
        this.title = '修改合集'
      })
    },
    /** 提交按钮 */
    submitForm() {
      //注入字典值
      this.classifyOption.forEach(e => {
        if (e.dictCode === this.form.classify) {
          this.form.classifyStr = e.dictLabel
        }
      })
      if (this.form.id != null) {
        updateCompilation(this.form).then(response => {
          this.$modal.msgSuccess('修改成功')
          this.open = false
          this.getList()
        })
      } else {
        addCompilation(this.form).then(response => {
          this.$modal.msgSuccess('新增成功')
          this.open = false
          this.getList()
        })
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除合集编号为"' + ids + '"的数据项？').then(function () {
        return delCompilation(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('compilation/compilation/export', {
        ...this.queryParams
      }, `compilation_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
<style>
.information-title {
  color: #19d3ea;
  font-size: 12px;
  width: 100%; /*一定要设置宽度，或者元素内含的百分比*/
  overflow: hidden; /*溢出的部分隐藏*/
  white-space: nowrap; /*文本不换行*/
  text-overflow: ellipsis; /*ellipsis:文本溢出显示省略号（...）；clip：不显示省略标记（...），而是简单的裁切*/
}
</style>
